// 创建用户相关仓库
import { defineStore } from "pinia";
// 引入接口
import { reqLogin, reqUserInfo, reqLogout } from "@/api/user";
// 引入数据类型
import type {
  loginFormData,
  loginResponseData,
  userInfoResponseData,
} from "@/api/user/type";
import type { UserState } from "./types/type";
// 引入操作本地存储的方法(localStorage)
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
// 引入路由(常量路由)
import { constantRoute, asyncRoute, anyRoute } from "@/router/routes";
// 引入深拷贝方法
// @ts-ignore
import cloneDeep from "lodash/cloneDeep";
import router from "@/router";
// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}
const useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), // 用户唯一标识toten
      menuRoutes: constantRoute, // 仓库存储生成菜单需要的数组(路由)
      username: "",
      avatar: "",
      buttons: [], // 存储当前用户是否包含某一个按钮
    };
  },
  actions: {
    // 用户登陆的方法
    async userLogin(data: loginFormData) {
      // 登陆请求
      const result: loginResponseData = await reqLogin(data);
      // 登陆请求:成功200->token
      if (result.code === 200) {
        // pinia存储token
        this.token = result.data as string;
        // 持久化存储token
        SET_TOKEN(result.data as string);
        // 当前async函数返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(new Error(result.data));
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      // 获取用户信息进行存储仓库当中
      let {
        code,
        message,
        data: { name, avatar, routes, buttons },
      }: userInfoResponseData = await reqUserInfo();
      if (code === 200) {
        this.username = name;
        this.avatar = avatar;
        this.buttons = buttons;
        // 计算当前用户需要展示的异步路由
        let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), routes);
        // 菜单的数据
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute];
        // 目前路由器管理的只有常量路由
        [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return "ok";
      } else {
        return Promise.reject(new Error(message));
      }
    },
    // 退出登陆
    async userLoginOut() {
      let result: any = await reqLogout();
      if (result.code === 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  getters: {},
});
// 对外暴露用户相关仓库
export default useUserStore;
